package com.sanley.coronavirus.service;/*
Created by shkstart on 2020/3/15.
*/

import com.sanley.coronavirus.bo.MyUserDetails;
import com.sanley.coronavirus.common.utils.JwtUtils;
import com.sanley.coronavirus.dao.UserDao;
import com.sanley.coronavirus.entity.Authentication;
import com.sanley.coronavirus.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    private UserDao userDao;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userDao.findByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException(s);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        List<Authentication> authentications = user.getAuthenticationList();
        for (Authentication authentication : authentications) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + authentication.getName()));
        }
        //将角色放入信息放入redis中
        redisTemplate.opsForValue().set("authorities:" + user.getUsername(), authorities, JwtUtils.getExpirationTime(), TimeUnit.MILLISECONDS);

        return new MyUserDetails(user);
    }
}
